package com.hex.ds.hdrs.common.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSON;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Package: com.hex.ds.hdtp.core.app.common.util
 * @ClassName ExcelDownUtil
 * @Description: 导出EXCEL工具-先生成EXCEL再下载
 * @Author: wz.li
 * @Date 2023/2/26 20:43
 * @Version v2.0.2
 **/
public class ExcelDownUtil {

    public static void generatedExcel(List dataList, String templateFilePath, String downloadPath){
        try {
            Workbook workbook = getWorkbook(dataList, templateFilePath);
            FileOutputStream fileOutputStream = new FileOutputStream(downloadPath);
            workbook.write(fileOutputStream);
            fileOutputStream.flush();
        } catch (Exception e) {
            throw new RuntimeException("生成EXCEL失败" + e.getMessage());
        }
    }

    private static Workbook getWorkbook(List dataList, String templateFilePath) {
        // 读取模板
        final TemplateExportParams templateExportParams = new TemplateExportParams(templateFilePath);
        // 获取导出数据
        Map<Integer, List<Map<String, Object>>> sheetMap = getDownloadData(dataList);
        // 生成数据
        return ExcelExportUtil.exportExcelClone(sheetMap, templateExportParams);
    }

    private static Map<Integer, List<Map<String, Object>>> getDownloadData(List dataList) {
        final Map<Integer, List<Map<String, Object>>> sheetMap = new HashMap<>();
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("list", dataList.stream().map(t -> JSON.parseObject(JSON.toJSONString(t), Map.class)).collect(Collectors.toList()));
        dataMap.put("sheetName", "Sheet");
        sheetMap.put(0, Arrays.asList(dataMap));
        return sheetMap;
    }
}
